import re
word_list = []
an_dick = {}

# 提取单词
def word(line):
    global word_list
    j = 0
    while j < len(line):
        if line[j].isalpha():
            for k in range(j, len(line)):
                if line[k].isalpha():
                    continue
                else:
                    word_list.append(line[j:k])
                    j = j + len(line[j:k])
                    break
        else:
            j = j + 1


def myFunc(e):
    return e['counts']


# 输出
with open('Walden.txt', 'r+', encoding='utf-8') as f:
# with open('test.txt', 'r+', encoding='utf-8') as f:
    for i in f:
        word(i.lower())

an_list = []
# 去重
only_list = list(set(word_list))
for i in only_list:
    count = word_list.count(i)
    an_list.append({'word': i, 'counts': count})
    an_dick[i] = count


# 统计
an_list.sort(key=myFunc, reverse=True)

# 输出
# print(an_dick)

# 排序输出
for i in an_list:
    print(f"{i['word']}，出现{i['counts']}次")

